package com.example.controller;

import com.example.entity.OrderType;
import com.example.service.FareCalculator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
@RequestMapping("/api/map")
public class MapController {

    @Value("${amap.key:ffcad56af852b5f4284e95f89a287852}")
    private String amapKey;

    private final RestTemplate restTemplate = new RestTemplate();
    
    @Autowired
    private FareCalculator fareCalculator;

    @Operation(summary = "获取路径规划信息", description = "根据起终点坐标获取路径规划和预估费用信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取路径规划信息"),
            @ApiResponse(responseCode = "400", description = "无效的请求参数"),
            @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/direction")
    public ResponseEntity<?> getDirection(
            @RequestParam double originLat,
            @RequestParam double originLng,
            @RequestParam double destinationLat,
            @RequestParam double destinationLng,
            @RequestParam int vehicleType) {
        
        try {
            // 打印接收到的参数
            System.out.println("收到路径规划请求，参数：" +
                    "originLat=" + originLat + ", originLng=" + originLng +
                    ", destinationLat=" + destinationLat + ", destinationLng=" + destinationLng +
                    ", vehicleType=" + vehicleType);
            
            // 高德API的origin和destination参数的格式是"经度,纬度"，注意经度在前，纬度在后
            // 增加show_fields参数获取完整的路径信息
            String url = String.format("https://restapi.amap.com/v5/direction/driving?" +
                    "key=%s&origin=%.6f,%.6f&destination=%.6f,%.6f&show_fields=polyline,steps",
                    amapKey, originLng, originLat, destinationLng, destinationLat);
            
            System.out.println("发送高德API请求：" + url);
            
            Map<String, Object> response = restTemplate.getForObject(url, Map.class);
            System.out.println("高德API响应状态：" + (response != null ? response.get("status") : "无响应"));
            
            if (response != null && "1".equals(response.get("status"))) {
                Map<String, Object> route = (Map<String, Object>) response.get("route");
                
                if (route != null && route.containsKey("paths") && ((java.util.List<?>) route.get("paths")).size() > 0) {
                    java.util.List<?> paths = (java.util.List<?>) route.get("paths");
                    System.out.println("获取到" + paths.size() + "条路径");
                    
                    // 获取第一条路径的结构，便于调试
                    if (paths.size() > 0) {
                        Map<String, Object> firstPath = (Map<String, Object>) paths.get(0);
                        System.out.println("第一条路径包含的字段: " + String.join(", ", firstPath.keySet()));
                        if (firstPath.containsKey("steps")) {
                            java.util.List<?> steps = (java.util.List<?>) firstPath.get("steps");
                            System.out.println("第一条路径包含 " + steps.size() + " 个步骤");
                            if (steps.size() > 0) {
                                Map<String, Object> firstStep = (Map<String, Object>) steps.get(0);
                                System.out.println("第一个步骤包含的字段: " + String.join(", ", firstStep.keySet()));
                            }
                        }
                    }
                    
                    // 获取所有路径的信息
                    java.util.List<Map<String, Object>> pathResults = new java.util.ArrayList<>();
                    
                    for (int i = 0; i < paths.size(); i++) {
                        Map<String, Object> path = (Map<String, Object>) paths.get(i);
                        
                        // 获取距离和时间，处理可能为空的情况
                        int distance = 0;
                        int duration = 0;
                        
                        if (path.containsKey("distance") && path.get("distance") != null) {
                            distance = Integer.parseInt(path.get("distance").toString());
                        }
                        
                        // 注意：V5 API可能没有直接返回duration，需要从其他字段获取或估算
                        if (path.containsKey("duration") && path.get("duration") != null) {
                            duration = Integer.parseInt(path.get("duration").toString());
                        } else if (path.containsKey("cost") && path.get("cost") != null) {
                            // 尝试从cost字段中获取duration
                            Map<String, Object> cost = (Map<String, Object>) path.get("cost");
                            if (cost != null && cost.containsKey("duration") && cost.get("duration") != null) {
                                duration = Integer.parseInt(cost.get("duration").toString());
                            } else {
                                // 如果没有duration字段，根据距离估算时间（假设平均速度为40km/h）
                                duration = (int) (distance / 1000.0 * 60 / 40);
                            }
                        } else {
                            // 如果没有duration和cost字段，根据距离估算时间
                            duration = (int) (distance / 1000.0 * 60 / 40);
                        }
                        
                        // 创建一个临时订单对象用于计算费用
                        com.example.entity.Order tempOrder = new com.example.entity.Order();
                        tempOrder.setDistance(distance / 1000.0); // 转换为公里
                        tempOrder.setDuration(duration / 60); // 转换为分钟
                        tempOrder.setType(OrderType.values()[vehicleType - 1]);
                        
                        // 计算预估费用
                        double fare = fareCalculator.calculate(tempOrder);
                        
                        // 添加路径结果
                        Map<String, Object> pathResult = new java.util.HashMap<>();
                        pathResult.put("distance", distance / 1000.0);
                        pathResult.put("duration", duration); // 不除以60，保留原始秒数
                        pathResult.put("fare", fare);
                        pathResult.put("path", path);
                        pathResult.put("pathIndex", i);
                        
                        pathResults.add(pathResult);
                    }
                    
                    // 返回所有路径信息
                    Map<String, Object> result = new java.util.HashMap<>();
                    result.put("paths", pathResults);
                    result.put("origin", route.get("origin"));
                    result.put("destination", route.get("destination"));
                    result.put("taxi_cost", route.get("taxi_cost"));
                    
                    return ResponseEntity.ok(result);
                }
            } else {
                String errorInfo = "高德API调用失败: " + (response != null ? response.get("info") : "无响应");
                System.out.println(errorInfo);
                return ResponseEntity.badRequest().body(errorInfo);
            }
            
            return ResponseEntity.badRequest().body("无法获取路径规划信息");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误：" + e.getMessage());
        }
    }
} 